
from PyQt5.QtCore import QObject, pyqtSignal, pyqtSlot
from src.utils.crawler import fetch_servant_audios


class AudioLinksWorker(QObject):
    links_ready = pyqtSignal(list, str, str)
    log_signal = pyqtSignal(str)
    finished = pyqtSignal()

    def __init__(self, page_url, sid, name):
        super().__init__()
        self.page_url = page_url
        self.sid = sid
        self.name = name
        self._is_cancelled = False

    def cancel(self):
        self._is_cancelled = True

    @pyqtSlot()
    def start(self):
        try:
            if self._is_cancelled: return
            self.log_signal.emit(f"[INFO] 正在抓取 {self.name} 的语音链接...")
            links = fetch_servant_audios(self.page_url, return_pairs=True)
            if self._is_cancelled: return
            self.log_signal.emit(f"[INFO] {self.name}: 找到 {len(links)} 条语音链接")
            self.links_ready.emit(links, self.sid, self.name)
        except Exception as e:
            if self._is_cancelled: return
            self.log_signal.emit(f"[ERROR] 获取 {self.name} 语音链接失败: {e}")
            self.links_ready.emit([], self.sid, self.name)
        finally:
            self.finished.emit()